<template>
  <div class="camera">
    <van-nav-bar
      title="智能核保助手"
      fixed
      placeholder
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- <div>
     	<van-icon @click="scanFlag = true;" name="scan" size="24" color="#000" class="v-cion-class"/>
    </div>
    <van-action-sheet
      v-model="scanFlag"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="selectScan"
    /> -->

    <!-- ---------------------- -->

    <!-- 上传图片、视频 -->
        <!-- <h1 class="title">上传图片:</h1>
        <van-field class="titleImg" readonly input-align="right">
          <template #button>
            <div style="display: flex;">
              <div class="avatar" style="width:80px;height:80px;margin-right:20px;">
                <CropperH5 ref="avatarImage" :fixedNumber="[1,1]" @getImageUrl='getAvatarImageUrl1' :image='avatarImage' />
              </div>
              <div class="avatar" style="width:80px;height:80px;">
                <CropperH5 ref="avatarImage" :fixedNumber="[1,1]" @getImageUrl='getAvatarImageUrl2' :image='avatarImage' />
              </div>
            </div>
          </template>
        </van-field> -->

    <!-- -------------------------------- -->

    <!-- <van-uploader :after-read="afterRead" /> -->

    <van-uploader :after-read="afterRead">
      <div class="camerabox">
        <img :src="imgSrc" alt="">
        <span>&nbsp;上传图片</span>
      </div>
      <!-- <van-button icon="plus" type="primary">上传文件</van-button> -->
    </van-uploader>

    <p class="tipBox">请注意截取体检报告中<span style="color:#eb3433">{{baseData.projectVal}}</span>的内容。</p>

    <!-- :style='{width: `${imgObj.width}px`, height: `${imgObj.height}px`}' -->
    <div class="cropper" :style='{maxwidth: "750px", height: "50vh"}'>
      <vueCropper
        ref="cropper"
        :img="option.img"
        :outputSize="option.outputSize"
        :outputType="option.outputType"
        :canScale='option.canScale'
        :autoCrop='option.autoCrop'
        :autoCropWidth='option.autoCropWidth'
        :autoCropHeight='option.autoCropHeight'
        :canMoveBox='option.canMoveBox'
        :canMove='option.canMove'
        :centerBox='option.centerBox'
        :info='option.info'
        :fixedBox='option.fixedBox'
        
      ></vueCropper>
    </div>

    <!-- <img :src='previewImg'  alt="" class='previewImg'> -->

    <div class="btnbox">
      <div class="btn2" @click="handleClick">确认截图</div>
    </div>
    <!-- <img :src="resImg" alt="" v-if="resImg" class='previewImg'> -->


  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import CropperH5 from '@/components/cropper.vue'
import camera from "@/assets/img/icon/camera.png"
import { recognizeApi } from "@/api/requestApi"; //调接口
export default {
  name:"camera",
  components:{
    CropperH5,
    VueCropper
  },
  
  data(){
    return{
      baseData: {
        projectVal: '项目名哈哈哈哈'
      },
      scanFlag:false,
      actions: [{	name: '拍照',id: 0},{	name: '相册选图',id: 1}],
      avatarImage: "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=319223871,3949806150&fm=26&gp=0.jpg",
      img1: '',
      img2: '',
      imgObj: {
        width:0,
        height:0
      },
      imgSrc:camera,
      option: {
        //img: require('../assets/preview.jpg'), // 裁剪图片地址，这里可以本地图片或者链接，链接不用require
        img:"", // 裁剪图片地址，这里可以本地图片或者链接，链接不用require
        outputSize: 1, // 裁剪生成图片质量
        outputType: 'jepg', // 裁剪生成图片格式
        canScale: true, // 图片是否允许滚轮播放
        autoCrop: true, // 是否默认生成截图框 false
        info: false, // 是否展示截图框信息
        autoCropWidth: 350, // 生成截图框的宽度
        autoCropHeight: 200, // 生成截图框的高度
        canMoveBox: true, // 截图框是否可以拖动
        fixedBox: false, // 固定截图框的大小
        canMove: false, // 上传图片是否可拖动
        centerBox: true, // 截图框限制在图片里面
      },
      previewImg: null, // 预览后的图片
      resImg: "",
      params: {},

    }
  },

  watch: {
    // 'option.img': {
    //   handler: function (val) {
    //     const that = this
    //     const img = new Image()
    //     img.src = val
    //     img.onload  = function () {
    //       that.imgObj.width = this.width
    //       that.imgObj.height = this.height
    //     }
    //   },
    //   immediate: true
    // }
  },

  created(){
    this.baseData = JSON.parse(sessionStorage.getItem('baseData')) || this.baseData;
    console.log('this.baseData',this.baseData);
    // 获取路由参数
    this.params = this.$route.params.newParams;
  },

  methods:{

    onClickLeft() {
      this.$router.go(-1);
    },

    // realTime (data) {
    //  console.log(data)
    //   const that = this
    //   that.previewImg = data.url
    // },

    afterRead(file) {
      console.log('file',file);
      // 此时可以自行将文件上传至服务器
      this.option.img = file.content
      // console.log("file.file",file.file);
    },

    //确认截图按钮
    handleClick () {
      this.$refs.cropper.getCropData(data => {
        console.log('data--',data);
        this.resImg = data;
        this.ocrClk();
        sessionStorage.setItem("base64Data",JSON.stringify(data));
      })
    },

    //ocr识别
    ocrClk(){
      
      this.$store.commit('loading/SET_LOADING',true);
      let blobToFile = this.base64ImgtoFile(this.resImg,"blob");
      console.log("blobToFile",blobToFile);
      let fd = new FormData();
      fd.append("imageFile", blobToFile);
      fd.append("itemsCode", this.baseData.projectCde);
      fd.append("identifying",  'ILMP-AUS-ASSISTANT-APPNDinRgij');
      fd.append("pictureType",  2);
      recognizeApi(fd).then((res) => {
        this.$store.commit('loading/SET_LOADING',false);
        if (res.data.resultCode === 200) {
          this.$toast("识别成功");
          this.$router.push({path:"/redact"})
        }else{
          this.$toast("识别失败");
        }
      }).catch((err) => {
          this.$toast("识别失败");
          this.$store.commit('loading/SET_LOADING',false);
      });
    },


    base64ImgtoFile(dataurl, filename) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },

    realTime (data) {
      const that = this
      // this.$refs.cropper.getCropBlob(data => {
      // // 这里data数据为Blob类型，blobToDataURI方法转换成base64
      //   this.blobToDataURI(data, function(res) {
      //     that.previewImg = res
      //   })
      // })
    }, 

    blobToDataURI(blob, callback) {
       var reader = new FileReader();
       reader.readAsDataURL(blob);
       reader.onload = function (e) {
          callback(e.target.result);
       }
    },


    
     handleDownload (url) {
      var a = document.createElement("a"); // 生成一个a元素
      var event = new MouseEvent("click"); // 创建一个单击事件
      a.download = "photo"; // 设置图片名称, 这里可以自定义，也可以获取图片名称进行修改
      a.href = url; // 将生成的URL设置为a.href属性
      a.dispatchEvent(event); // 触发a的单击事件
    }
,



      //获取头像url
    async getAvatarImageUrl1(file) {
      var formData = new FormData();
      formData.append('file', file); // 固定格式
      const res = await upload(formData)
      if (res) {
        this.img1 = (res.data[0])
        console.log(res);
      }
    },
    async getAvatarImageUrl2(file) {
      var formData = new FormData();
      formData.append('file', file); // 固定格式
      const res = await upload(formData)
      if (res) {
        this.img2 = (res.data[0])
        console.log(res);
      }
    },




    selectScan(action){
      if (window.plus) {    
          // 在这里调用5+ API   
          console.log(1111);
          this.plusReady();   
      } else {    
          console.log(2222);
          // 兼容老版本的plusready事件    
          document.addEventListener('plusready', this.plusReady(), false);    
      }

      // if (action.id === 0) {
      //   // 获取摄像头对象
      //   const cmr = plus.camera.getCamera();
      //   // 唤醒摄像头拍摄
      //   cmr.captureImage((path) => {
      //     // 获取图片地址
      //     plus.io.resolveLocalFileSystemURL(path, (entry) => {
      //       router.push({
      //         path: '/cropper',
      //         query: {
      //           imgUrl: entry.toLocalURL(),
      //         },
      //       });
      //     }, () => {
      //       // 读取文件失败的场合
      //       proxy.$toast('读取拍照文件错误');
      //     });
      //   }, () => {
      //     // 关闭摄像头的场合
      //   }, {
      //     optimize: false, // 不优化图片
      //     index: '1', // 选择后摄像头
      //   });
      // } else {
      //   // 调用h5+plus方法打开手机相册选择图片
      //   plus.gallery.pick((path) => {
      //     router.push({
      //       path: '/cropper',
      //       query: {
      //         imgUrl: path,
      //       },
      //     });
      //   },function () {
      //     // 取消选择图片的场合
      //   },{system:false});// 最多选择1张图片
      // }
    },

    plusReady() {
      console.log(333);
      // 在这里调用plus api
      plus.device.getInfo({
          success: function (e) {
             alert('getDeviceInfo success');
          },
          fail: function (e) {
             alert('getDeviceInfo failed');
          }
      })
    }
  }


}
</script>

<style scoped>

  .camerabox{
    display: flex;
    justify-content: center;
    margin: 20px auto;
    width: 100%;
    padding: 10px;
    border: 1px dashed #cecece;
    border-radius: 25px;
    color: #eb3433;
  } 

  .camerabox img{
    width: 20px;
    height: 20px;
  }

  .tipBox{
    font-weight: 600;
    margin: 10px;
  }

  .btnbox{
    margin-top: 50px;
    display: flex;
    justify-content: space-around;
  }

  .btnbox div{
    width: 180px;
    height: 40px;
    line-height: 40px;
  }

  .btnbox .btn1{
    background-color: #fff;
    border: 1px solid #eb3433;
    color: #eb3433;
    border-radius: 6px;
  }

  .btnbox .btn2{
    background-color: #eb3433;
    border: 1px solid #eb3433;
    color: #fff;
    border-radius: 6px;
  }

  /* ::v-deep .titleImg {
    padding: 10px 0;
  }

  ::v-deep .titleImg .van-cell__value{
    display: flex;
  }

  ::v-deep .titleImg .van-field__control{
      display: none;
  }

  ::v-deep .titleImg ::v-deep .cropper-crop-box{
      width: 300px;
      height: 300px;
  } */

  /* .previewImg{
    width: 300px;
    max-width: 750px;
  } */




</style>